/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.PrimaryGenerater;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.*;
import com.jeeplus.modules.fee.service.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 付款单Controller
 * @author weisong
 * @version 2017-09-20
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/payment")
public class PaymentController extends BaseController {

	@Autowired
	private PaymentService paymentService;
	@Autowired
	private PaymentDetailService paymentDetailService;
	@Autowired
	private PaymentPayableDetailService paymentPayableDetailService;
	@Autowired
	private PayInvoiceService payInvoiceService;
	@Autowired
	private PayableService payableService;
	@Autowired
	private PayInvoiceDetailService payInvoiceDetailService;
	@Autowired
	private ConsignorService consignorService;

	@ModelAttribute
	public Payment get(@RequestParam(required=false) String id) {
		Payment entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = paymentService.get(id);
		}
		if (entity == null){
			entity = new Payment();
		}
		return entity;
	}
	
	/**
	 * 付款单列表页面
	 */
	@RequiresPermissions("fee:payment:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/fee/paymentList";
	}
	
		/**
	 * 付款单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:payment:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Payment payment, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Payment> page = paymentService.findPage(new Page<Payment>(request, response), payment); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑付款单表单页面
	 */
	@RequiresPermissions(value={"fee:payment:view","fee:payment:add","fee:payment:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Payment payment, Model model) {
		model.addAttribute("payment", payment);
		if(StringUtils.isBlank(payment.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		if(null != payment.getId()){
			PaymentPayableDetail fppd = new PaymentPayableDetail();
			fppd.setFeePayment(payment);
			List<PaymentPayableDetail> PaymentPayableDetails = paymentPayableDetailService.findList(fppd);
			model.addAttribute("PaymentPayableDetails", PaymentPayableDetails);
			model.addAttribute("sign", "sign");
		}
		List<PaymentDetail> list = paymentDetailService.findPaymentDetailById(payment.getId());
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("target", request.getParameter("target"));
		if (null != list && list.size() > 0) {
			model.addAttribute("list", list);
			model.addAttribute("flag", "payment");
		} else {
			//获取发票主表id
			if (null != request.getParameter("ids")) {
				List<PayInvoiceDetail> allNewInvoice = new ArrayList<PayInvoiceDetail>();
				String ids[] = request.getParameter("ids").split(",");
				System.out.println(ids);
				if (null != ids || ids.length != 0) {
					//传过来的发票主表id
					for (String id : ids) {
						PayInvoice invoice = payInvoiceService.get(id);
						//根据发票主表id获取发票子表
						PayInvoiceDetail temp = new PayInvoiceDetail();
						temp.setFeePayInvoice(invoice);
						List<PayInvoiceDetail> invoiceDetails = payInvoiceDetailService.findList(temp);
						for (PayInvoiceDetail invoiceDetail : invoiceDetails) {
							//获取付款单子表
							List<PaymentDetail> details = paymentDetailService.findAllByPayInvoiceDetail(invoiceDetail.getId());
							Double vcaMoney = 0.0;
							for (PaymentDetail detail : details) {
								vcaMoney += detail.getTheVcaMoney();
							}
							invoiceDetail.setVcaMoney(vcaMoney);
							allNewInvoice.add(invoiceDetail);
						}
					}
					model.addAttribute("list", allNewInvoice);
				}
			}
		}
		return "modules/fee/paymentForm";
	}

	/**
	 * 保存付款单
	 */
	@RequiresPermissions(value={"fee:payment:add","fee:payment:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Payment payment, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, payment)){
			return form(payment, model);
		}
		if(!payment.getIsNewRecord()){//编辑表单保存
			Payment t = paymentService.get(payment.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(payment, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			paymentService.save(t);//保存

			//将结算单的数据保存到付款单子表
			String ids_payable = request.getParameter("ids_payable");	//接收表单的值
			if(StringUtils.isNotEmpty(ids_payable)){
				//调用保存付款单子表【引入结算单时】
				savePayable(payment,ids_payable);
				//引入结算单保存时对结算单的回填
				if(payment.getStatus() != 0){
					BackFillPayableStatusAndMoney(payment);
				}
			}
			//获取引入的发票明细
			PaymentDetail fpd = null;
			String[] _ids = request.getParameter("ids").split(",");	//将form页面取的id值循环遍历
			//本次核销总金额
			double theVcaMoney = 0.0;
			System.out.println("本次核销总金额:"+theVcaMoney);
			if (_ids.length != 0) {
				for (String id : _ids) {
					if (StringUtils.isNotEmpty(id)) {
						double vcaMoney = 0.0;
						fpd = new PaymentDetail();
						String[] str = id.split("_"); // 1232323 20032323 456[发票id 发票明细id// 本次核销金额]
						System.out.println(str.length + "===========================");
						if (StringUtils.isNotEmpty(str[0])) {
							PayInvoice invoice = payInvoiceService.get(str[0]);
							fpd.setFeePayInvoice(invoice);
							fpd.setInvoiceNo(invoice.getEntityNo());
						}
						if (StringUtils.isNotEmpty(str[1])) {
							PayInvoiceDetail feePayInvoiceDetail = payInvoiceDetailService.get(str[1]);
							if(feePayInvoiceDetail == null){
								continue;
							}
							fpd.setFeePayInvoiceDetail(feePayInvoiceDetail);
							fpd.setInvoiceMoney(feePayInvoiceDetail.getInvMoney());
							if (null == feePayInvoiceDetail.getFeePayInvoice().getVcaMoney()) {
								fpd.setVcaMoney(vcaMoney);
							} else {
								//根据发票主表id获取付款单子表
								List<PaymentDetail> payDetail = paymentDetailService.findList(fpd);
								for (int i = 0; i < payDetail.size(); i++) {
									PaymentDetail pd = payDetail.get(i);
									vcaMoney += pd.getTheVcaMoney();
								}
								fpd.setVcaMoney(vcaMoney);
							}
						}
						if (StringUtils.isNotEmpty(str[2])) {
							fpd.setTheVcaMoney(Double.parseDouble(str[2]));
							theVcaMoney +=Double.parseDouble(str[2]);
						}
						fpd.setFeePayment(payment);
						paymentDetailService.save(fpd);
					}
				}
			}
			addMessage(redirectAttributes, "保存付款单成功");
		}else{//新增表单保存
			//生成单号
			String number="";
			Payment pay = paymentService.findPaymentNoAndPaymentDate();
			Format format1 = new SimpleDateFormat("yyyyMMdd");  	//初始化时间格式
			//比较结算日期是否和现在的日期相等
			if (null == pay) {
				number = PrimaryGenerater.getInstance().generaterNextNumber("FKDH", null);
			} else {
				if (String.valueOf(format1.format(pay.getPaymentDate())).equals(String.valueOf(format1.format(new Date())))) {
					number = PrimaryGenerater.getInstance().generaterNextNumber("FKDH", pay.getPaymentNo());
				} else {
					number = PrimaryGenerater.getInstance().generaterNextNumber("FKDH", null);
				}
			}
			payment.setPaymentNo(number);
			String ids= request.getParameter("ids");	//将form页面取的id值循环遍历
			if(StringUtils.isEmpty(ids) || StringUtils.isEmpty(ids.trim().replaceAll(",",""))){
				//手动输入的付款金额,没有引入子表
				payment.setOperateType(Payment.noDetail);
				paymentService.save(payment);//保存
			}else{
				//引入后，累加明细自动填写的付款金额
				String[] _ids = ids.split(",");	//将form页面取的id值循环遍历
				payment.setOperateType(Payment.haveDetail);
				//根据结算方名称查询id
				Consignor feeConsignor = consignorService.findUniqueByProperty("name",payment.getPayee().getName());
				payment.setPayee(feeConsignor);
				paymentService.save(payment);//保存
				//保存发票子表到付款单明细表
				if(StringUtils.isNotEmpty(ids)){
					savePayInvoiceDetail(payment,ids);
				}
			}
			//将结算单的数据保存到付款单子表
			String ids_payable = request.getParameter("ids_payable");	//接收表单的值
			if(StringUtils.isNotEmpty(ids_payable)){
				payment.setOperateType(Payment.haveDetail);
				//根据结算方名称查询id
				Consignor feeConsignor = consignorService.findUniqueByProperty("name",payment.getPayee().getName());
				payment.setPayee(feeConsignor);
				paymentService.save(payment);//保存
				//调用保存付款单子表【引入结算单时】
				savePayable(payment,ids_payable);
			}
			addMessage(redirectAttributes, "保存付款单成功");
			String type = request.getParameter("typeTarget");
			System.out.println(type);
			if(null != type){
				if(type.equals("invoice")) {
					return "redirect:" + Global.getAdminPath() + "/fee/payInvoice/list";
				}else{
					return "redirect:"+Global.getAdminPath()+"/fee/payment/?repage";
				}
			}
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payment/?repage";
	}
	
	/**
	 * 删除付款单
	 */
	@ResponseBody
	@RequiresPermissions("fee:payment:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Payment payment, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		paymentService.delete(payment);
		j.setMsg("删除付款单成功");
		return j;
	}
	
	/**
	 * 批量删除付款单
	 */
	@ResponseBody
	@RequiresPermissions("fee:payment:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//删除付款单时删除子表数据
			PaymentDetail temp = new PaymentDetail();
			temp.setFeePayment(paymentService.get(id));
			List<PaymentDetail> list = paymentDetailService.findList(temp);
			for (int i = 0; i < list.size(); i++) {
				//删除付款单明细表
				paymentDetailService.delete(list.get(i));
			}
			PaymentPayableDetail temp1 = new PaymentPayableDetail();
			temp1.setFeePayment(paymentService.get(id));
			List<PaymentPayableDetail> list1 = paymentPayableDetailService.findList(temp1);
			for (int i = 0; i < list1.size(); i++) {
				//删除付款单明细表
				paymentPayableDetailService.delete(list1.get(i));
			}
			paymentService.delete(paymentService.get(id));
		}
		j.setMsg("删除付款单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:payment:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Payment payment, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "付款单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Payment> page = paymentService.findPage(new Page<Payment>(request, response, -1), payment);
    		new ExportExcel("付款单", Payment.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出付款单记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:payment:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Payment> list = ei.getDataList(Payment.class);
			for (Payment payment : list){
				try{
					paymentService.save(payment);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条付款单记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条付款单记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入付款单失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payment/?repage";
    }
	
	/**
	 * 下载导入付款单数据模板
	 */
	@RequiresPermissions("fee:payment:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "付款单数据导入模板.xlsx";
    		List<Payment> list = Lists.newArrayList(); 
    		new ExportExcel("付款单数据", Payment.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/payment/?repage";
    }

	/**
	 * 修改状态
	 * @param ids 付款单主表id
	 * @return
	 */
	@RequestMapping(value = "updateStatus")
	@ResponseBody
	public AjaxJson updateStatus(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			//获得付款单主表
			Payment feePayment = paymentService.get(id);
			//更新状态
			if(feePayment.getStatus() < Payment.updateStatus3){
				paymentService.updateStatusById(Payment.updateStatus3, id);
			}
			//查询付款单子表
			PaymentDetail fpd = new PaymentDetail();
			fpd.setFeePayment(feePayment);
			List<PaymentDetail> feePaymentDetails = paymentDetailService.findList(fpd);
			if(feePaymentDetails.size()>0) {
				//调用回填发票和结算单方法
				BackFillOperations(feePayment);
			}
			//查询付款单--结算单子表
			PaymentPayableDetail fppd = new PaymentPayableDetail();
			fppd.setFeePayment(feePayment);
			List<PaymentPayableDetail> paymentPayableDetails = paymentPayableDetailService.findList(fppd);
			if(paymentPayableDetails.size()>0) {
				//引入结算单保存时对结算单的回填
				BackFillPayableStatusAndMoney(feePayment);
			}
		}
		j.setMsg("修改状态成功");
		return j;
	}
	/**
	 * 修改状态
	 * @param id 付款单主表id
	 * @return
	 */
	@RequestMapping(value = "updateStatusTwo")
	public String updateStatusTwo(String id) {
		//获得付款单主表
		Payment feePayment = paymentService.get(id);
		//更新状态
		if(feePayment.getStatus() < Payment.updateStatus3){
			paymentService.updateStatusById(Payment.updateStatus3, id);
		}
		//查询付款单子表
		PaymentDetail fpd = new PaymentDetail();
		fpd.setFeePayment(feePayment);
		List<PaymentDetail> feePaymentDetails = paymentDetailService.findList(fpd);
		if(feePaymentDetails.size()>0) {
			//调用回填发票和结算单方法
			BackFillOperations(feePayment);
		}
		//查询付款单--结算单子表
		PaymentPayableDetail fppd = new PaymentPayableDetail();
		fppd.setFeePayment(feePayment);
		List<PaymentPayableDetail> paymentPayableDetails = paymentPayableDetailService.findList(fppd);
		if(paymentPayableDetails.size()>0) {
			//引入结算单保存时对结算单的回填
			BackFillPayableStatusAndMoney(feePayment);
		}
		return "redirect:" + Global.getAdminPath() + "/fee/payment/form?id=" + id;
	}

	/**
	 * 付款单引入结算单更新结算单的状态和核销金额
	 */
	public void BackFillPayableStatusAndMoney(Payment feePayment) {
		//根据付款单主表查询付款单--结算单子表
		PaymentPayableDetail detail = new PaymentPayableDetail();
		detail.setFeePayment(feePayment);
		List<PaymentPayableDetail> paymentDetails = paymentPayableDetailService.findList(detail);
		//循环遍历付款单--结算单明细表，根据应付结算单属性更新结算单
		if (paymentDetails.size() > 0) {
			//付款金额
			Double payMoney = feePayment.getPayMoney();
			for (PaymentPayableDetail fppd : paymentDetails) {
				//结算金额
				Double clearMoney = fppd.getClearingMoney();
				//获取本次核销金额
				Double theVca = fppd.getTheVcaMoney() == null ? 0.0 : fppd.getTheVcaMoney();
				//查询结算单主表
				Payable payables = payableService.get(fppd.getFeePayable());
				//获取结算单的核销金额
				Double vca = payables.getVcaMoney()== null ? 0.0 : payables.getVcaMoney();
				//获取结算单的开票金额
				Double inv = payables.getInvoiceMoney()== null ? 0.0 : payables.getInvoiceMoney();
				if ((theVca+vca) < clearMoney) {
					//根据结算单id更新结算单的状态和核销金额[状态，开票金额，核销金额，未开票金额，未核销金额，id]
					payableService.updateMoneyAndStatusById(Receivables.updateStatus4, inv,
							(theVca+vca), (clearMoney-inv),
							(clearMoney - (theVca+vca)), fppd.getFeePayable().getId());
				}else{
					payableService.updateMoneyAndStatusById(Receivables.updateStatus5, inv,
							(theVca+vca), (clearMoney-inv), 0.0, fppd.getFeePayable().getId());
				}
			}
		}
	}


	/**
	 * 回填发票和结算单
	 * @param feePayment	付款单主表
	 */
	public void BackFillOperations(Payment feePayment){
		//获得付款单子表list
		PaymentDetail temp = new PaymentDetail();
		temp.setFeePayment(feePayment);
		List<PaymentDetail> fpds = paymentDetailService.findList(temp);
		if (null != fpds && fpds.size() > 0) {
			for (PaymentDetail fpDetail : fpds) {
				//开始回填应付发票的核销金额,并改变状态
				//获得发票主表
				PayInvoice feeInvoice = payInvoiceService.get(fpDetail.getFeePayInvoice());
				//发票主表已核销金额
				double vacMoney = feeInvoice.getVcaMoney()==null?0.0:feeInvoice.getVcaMoney();
				vacMoney += (fpDetail.getTheVcaMoney()==null?0.0:fpDetail.getTheVcaMoney());
				//更新核销金额和状态
				if (vacMoney == feeInvoice.getInvoiceMoney()) {
					payInvoiceService.updateVcaMoneyAndStatusById(vacMoney, PayInvoice.updateStatus2, feeInvoice.getId());
				} else if (vacMoney < feeInvoice.getInvoiceMoney() && vacMoney > 0) {
					payInvoiceService.updateVcaMoneyAndStatusById(vacMoney, PayInvoice.updateStatus1, feeInvoice.getId());
				}
				//开始回填应付结算单的核销金额，付款金额(与核销金额相等)并改变状态
				//获得发票子表，根据发票子表获得应付结算单
				Payable able = payableService.findByPamentDetailId(fpDetail.getId());
				double ableVca = able.getVcaMoney()==null?0.0:able.getVcaMoney();
				ableVca += (fpDetail.getTheVcaMoney()==null?0.0:fpDetail.getTheVcaMoney());
				//更新核销金额，状态，未核销金额
				if (ableVca == able.getClearingMoney()) {
					payableService.updateMoneyAndStatusById(Payable.updateStatus5, null, ableVca, null, 0.0, able.getId());
				} else if (ableVca < able.getClearingMoney() && ableVca > 0) {
					payableService.updateMoneyAndStatusById(Payable.updateStatus4, null, ableVca, null, able.getClearingMoney() - ableVca, able.getId());
				}
			}
		}
	}

	/**
	 * 付款单form页面的引入明细弹出框的确定按钮
	 */
	@RequestMapping(value = "addPayment")
	public @ResponseBody String addPayment(@RequestParam String ids, @RequestParam Integer type, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		// 如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/payInvoice/?repage";
		List<PayInvoiceDetail> list = new ArrayList<PayInvoiceDetail>();
		List<PayInvoiceDetail> invoiceDetails = new ArrayList<PayInvoiceDetail>();
		if (StringUtils.isNotEmpty(ids)) { // 判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					PayInvoiceDetail tempDetail = new PayInvoiceDetail();
					//根据发票id获取发票主表
					PayInvoice invoice = payInvoiceService.get(id);
					tempDetail.setFeePayInvoice(invoice);
					//根据发票获取发票子表
					invoiceDetails = payInvoiceDetailService.findList(tempDetail);
					for (PayInvoiceDetail invoiceDetail : invoiceDetails) {
						//获取付款单子表
						List<PaymentDetail> details = paymentDetailService.findAllByPayInvoiceDetail(invoiceDetail.getId());
						//获取本次核销金额
						Double vcaMoney = 0.0;
						for (PaymentDetail detail : details) {
							vcaMoney += detail.getTheVcaMoney();
						}
						//设置引入发票时的已核销金额
						invoiceDetail.setVcaMoney(vcaMoney);
					}
					list.addAll(invoiceDetails);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}

	/**
	 * 将结算单的数据保存到付款单子表
	 * @param feePayment
	 * @param ids_payable
	 */
	public void savePayable(Payment feePayment,String ids_payable){
		//分割ids
		String[] _ids = ids_payable.split(",");
		//循环遍历_ids
		if (_ids.length != 0) {
			for (String id : _ids) {
				//判断id不为空
				if (StringUtils.isNotEmpty(id)) {
					String[] ableIds = id.split("_");//结算单id_本次核销金额
					if(ableIds.length > 0){
						//根据id获取结算单数据
						Payable payable = payableService.get(ableIds[0]);
						if(payable!=null){
							//保存付款单--结算单子表
							PaymentPayableDetail feePaymentPayableDetail = new PaymentPayableDetail();
							//设置付款单主表
							feePaymentPayableDetail.setFeePayment(feePayment);
							//设置结算单
							feePaymentPayableDetail.setFeePayable(payable);
							feePaymentPayableDetail.setClearingNo(payable.getClearingNo());
							feePaymentPayableDetail.setBusyDate(payable.getBusyDate());
							feePaymentPayableDetail.setClearingMoney(payable.getClearingMoney());
							feePaymentPayableDetail.setFeeConsignor(payable.getPayee());
							feePaymentPayableDetail.setVcaMoney(payable.getVcaMoney());
							feePaymentPayableDetail.setTheVcaMoney(Double.parseDouble(ableIds[1]));
							feePaymentPayableDetail.setRemarks(payable.getRemarks());
							paymentPayableDetailService.save(feePaymentPayableDetail);
						}
					}
				}
			}
		}
	}

	/**
	 * 将发票子表保存到付款单明细表
	 */
	public void savePayInvoiceDetail(Payment feePayment,String ids){
		//保存到付款单明细表
		PaymentDetail fpd = null;
		String[] _ids = ids.split(",");	//将form页面取的id值循环遍历
		if (_ids.length != 0) {
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					double vcaMoney = 0.0;
					fpd = new PaymentDetail();
					String[] str = id.split("_"); // 1232323 20032323 456[发票id 发票明细id// 本次核销金额]
					System.out.println(str.length + "===========================");
					if (StringUtils.isNotEmpty(str[0])) {
						PayInvoice invoice = payInvoiceService.get(str[0]);
						fpd.setFeePayInvoice(invoice);
						fpd.setInvoiceNo(invoice.getEntityNo());
					}
					if (StringUtils.isNotEmpty(str[1])) {
						PayInvoiceDetail feePayInvoiceDetail = payInvoiceDetailService.get(str[1]);
						fpd.setFeePayInvoiceDetail(feePayInvoiceDetail);
						fpd.setInvoiceMoney(feePayInvoiceDetail.getInvMoney());
						PayInvoice pi =  payInvoiceService.get(feePayInvoiceDetail.getFeePayInvoice());
						if (null == pi.getVcaMoney()) {
							fpd.setVcaMoney(vcaMoney);
						} else {
							//根据发票主表id获取付款单子表
							List<PaymentDetail> payDetail = paymentDetailService.findList(fpd);
							for (int i = 0; i < payDetail.size(); i++) {
								PaymentDetail pd = payDetail.get(i);
								vcaMoney += pd.getTheVcaMoney();
							}
							fpd.setVcaMoney(vcaMoney);
						}
					}
					if (StringUtils.isNotEmpty(str[2])) {
						fpd.setTheVcaMoney(Double.parseDouble(str[2]));
					}
					fpd.setFeePayment(feePayment);
					paymentDetailService.save(fpd);
				}
			}
		}
	}

	/**
	 * 根据付款单主表id查询子表数据
	 * @return
	 */
	@RequestMapping(value = "findPaymentPayableDetailByPaymentId")
	public @ResponseBody
	List<PaymentPayableDetail> findPaymentPayableDetailByPaymentId(HttpServletRequest request){
		String paymentId = request.getParameter("id");
		List<PaymentPayableDetail> list = new ArrayList<PaymentPayableDetail>();
		PaymentPayableDetail detail = new PaymentPayableDetail();
		if(StringUtils.isNotEmpty(paymentId)){
			//获取主表数据
			Payment payment = paymentService.get(paymentId);
			detail.setFeePayment(payment);
			//获取子表数据
			list = paymentPayableDetailService.findList(detail);
		}
		return list;
	}

	/**
	 * 获取弹出窗口的数据
	 */
	@RequestMapping(value="findPayInvoiceList")
	public @ResponseBody
	List<PayInvoice> findList(PayInvoice feePayInvoice, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes){
		// 判断引入明细的状态是否为全部核销
		String _status = request.getParameter("status");
		//获取查询框输入的值[模糊查询]
		String clearUnit = request.getParameter("clearUnit");
		//获取结算单的值
		String payables = request.getParameter("tempPayables");
		if (_status != null) {
			Integer status = Integer.parseInt(_status);
			feePayInvoice.setStatus(status);//状态
		}
		if(StringUtils.isNotEmpty(clearUnit)){
			feePayInvoice.setInvoiceObj(clearUnit);//结算方
		}
		List<PayInvoice> list = new ArrayList<PayInvoice>();
		//结算单id
		if (StringUtils.isNotEmpty(payables)) {
			String[] ables = payables.split(",");
			if (ables.length > 0) {
				for (String ableId : ables) {
					feePayInvoice.setFeePayable(ableId);
					List<PayInvoice>  list1 =  payInvoiceService.findList(feePayInvoice);
					list.addAll(list1);
				}
			}
		} else{
			list = payInvoiceService.findList(feePayInvoice);
		}
		return list;
	}

	/**
	 * 删除付款单明细
	 * @param id 付款单子表id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "removePaymentDetail")
	public String removePaymentDetail(String id, RedirectAttributes redirectAttributes) {
		PaymentDetail feePaymentDetail = paymentDetailService.get(id);	//根据id查询数据
		//获取本次核销金额
		Double theVcaMoney = feePaymentDetail.getTheVcaMoney();
		//获取付款单主表
		Payment feePayment = paymentService.get(feePaymentDetail.getFeePayment());
		//获取付款单的总付款金额
		Double paymentMoney = feePayment.getPayMoney();
		//更新付款单主表的付款金额
		if (null != theVcaMoney && null != paymentMoney) {
			feePayment.setPayMoney((paymentMoney-theVcaMoney));
			paymentService.save(feePayment);
		}
		paymentDetailService.delete(feePaymentDetail);
		addMessage(redirectAttributes, "删除付款单明细成功");
		return "redirect:"+Global.getAdminPath()+"/fee/payment/form?id="+feePayment.getId();
	}

	/**
	 * 付款单获取结算单弹出窗口的数据
	 */
	@RequestMapping(value = "findAllPayable")
	public
	@ResponseBody
	List<Payable> findAllPayable(Payable feePayable, HttpServletRequest request, HttpServletResponse response) {
		// 判断应付结算单的状态[未开票]
		String _status = request.getParameter("status");
		//转换为int
		Integer status = Integer.parseInt(_status);
		//获input框输入的值[模糊查询]
		String clearUnit = request.getParameter("clearUnit");
		List<Payable> list = new ArrayList<Payable>();
		if (StringUtils.isNotEmpty(clearUnit)) {
			list = payableService.findAllByStatus(clearUnit, status);
		} else {
			list = payableService.findAllByStatus(null, status);
		}
		return list;
	}

	/**
	 * 付款单引入结算单明细时的确定按钮
	 */
	@RequestMapping(value = "addPayableDetails")
	public
	@ResponseBody
	String addPayableDetails(@RequestParam String ids, Model model, RedirectAttributes redirectAttributes) {
		//如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/payable/?repage";
		List<Payable> list = new ArrayList<Payable>();
		if (StringUtils.isNotEmpty(ids)) {    //判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Payable payble = payableService.get(id);
					list.add(payble);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}

	/**
	 * 删除付款单--结算单明细
	 * @param id 付款单--结算单子表id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "removePaymentPayableDetail")
	public String removePaymentPayableDetail(String id, RedirectAttributes redirectAttributes) {
		PaymentPayableDetail feePaymentPayableDetail = paymentPayableDetailService.get(id);	//根据id查询数据
		//获取本次核销金额
		Double theVcaMoney = feePaymentPayableDetail.getTheVcaMoney();
		//获取付款单主表
		Payment feePayment = paymentService.get(feePaymentPayableDetail.getFeePayment());
		//获取付款单的总付款金额
		Double paymentMoney = feePayment.getPayMoney();
		//更新付款单主表的付款金额
		if (null != theVcaMoney && null != paymentMoney) {
			feePayment.setPayMoney((paymentMoney-theVcaMoney));
			paymentService.save(feePayment);
		}
		paymentPayableDetailService.delete(feePaymentPayableDetail);
		addMessage(redirectAttributes, "删除付款单-结算单明细成功");
		return "redirect:"+ Global.getAdminPath()+"/fee/payment/form?id="+feePayment.getId();
	}






}